<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属题库" prop="questionBank">
        <el-input
          v-model="queryParams.questionBank"
          placeholder="请输入所属题库"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="generate_test_paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文件id" align="center" prop="fileId" />
      <el-table-column label="所属题库" align="center" prop="questionBank" />
      <el-table-column label="文件" align="center" prop="filePath" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edit']"
          >修改</el-button>
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['remove']"
          >删除</el-button>

          <el-button
            size="small"
            type="success"
            icon="excel"
            @click="showGeneratePaperDialog(scope.row)"
            v-hasPermi="['generate']"
          ><svg-icon icon-class="date"/>生成试题</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 生成试题弹窗 -->
    <el-dialog
      width="30%"
      title="生成试题"
      :visible.sync="innerVisible"
      append-to-body center>
      <!-- 内层表单 -->
      <el-form :model="generate_test_form" :rules="generate_test_rules" ref="generate_test_form" status-icon>

        <el-form-item label="试题名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="generate_test_form.name" placeholder="请输入试题名称" autocomplete="off" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="单选题数量" :label-width="formLabelWidth" prop="single">
          <el-input-number v-model="generate_test_form.single" :min="0"  label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="多选题数量" :label-width="formLabelWidth" prop="multiple">
          <el-input-number v-model="generate_test_form.multiple" :min="0"  label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="判断题数量" :label-width="formLabelWidth" prop="torF">
          <el-input-number v-model="generate_test_form.torF" :min="0"  label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="填空题数量" :label-width="formLabelWidth" prop="fillBlank">
          <el-input-number v-model="generate_test_form.fillBlank" :min="0"  label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="简答题数量" :label-width="formLabelWidth" prop="short">
          <el-input-number v-model="generate_test_form.short" :min="0"  label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="难易程度" :label-width="formLabelWidth" prop="difficulty">
          <el-select v-model="generate_test_form.difficulty" placeholder="试题难度">
            <el-option label="简单" value="0"></el-option>
            <el-option label="中等" value="1"></el-option>
            <el-option label="困难" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="generate_test_cancel">取 消</el-button>
        <el-button type="primary" @click="generate_test_submit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改生成试题文件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属题库" prop="questionBank">
          <el-input v-model="form.questionBank" placeholder="请输入所属题库" />
        </el-form-item>
        <el-form-item label="文件" prop="filePath">
          <file-upload v-model="form.filePath"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {EventBus} from '@/api/generateTest/eventBus'
import {
  listGenerate_test_paper,
  getGenerate_test_paper,
  delGenerate_test_paper,
  addGenerate_test_paper,
  updateGenerate_test_paper,
  generate
} from '@/api/generateTest/generate_test_paper'

export default {
  name: "Generate_test_paper",
  data() {
    return {
      // 生成试题弹窗数据
      innerVisible: false, // 控制弹窗的显示与隐藏
      generate_test_form: {
        generate_fileId: '', // 生成试题源文件id
        name: '',
        single: 0,
        multiple: 0,
        torF:0,
        fillBlank: 0,
        short: 0,
        difficulty: ''
      },
      dataList: {
        single: 10, // 示例值，需要根据实际情况调整
        multiple: 10, // 示例值，需要根据实际情况调整
        torF: 10,
        fillBlank: 10,
        short: 10, // 示例值，需要根据实际情况调整
      },
      generate_test_rules: {
        name: [{ required: true, message: '请输入试题名称', trigger: 'blur' }],
        single: [{ required: true, message: '请输入单选题数量', trigger: 'change' }],
        multiple: [{ required: true, message: '请输入多选题数量', trigger: 'change' }],
        torF: [{ required: true, message: '请输入判断题数量', trigger: 'change' }],
        fillBlank: [{ required: true, message: '请输入填空题数量', trigger: 'change' }],
        short: [{ required: true, message: '请输入简答题数量', trigger: 'change' }],
        difficulty: [{ required: true, message: '请选择难易程度', trigger: 'change' }]
      },
      formLabelWidth: '120px',

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedGeneratedExam: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生成试题文件表格数据
      generate_test_paperList: [],
      // 生成试题表格数据
      generatedExamList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        questionBank: null,
        filePath: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        questionBank: [
          { required: true, message: "所属题库不能为空", trigger: "blur" }
        ],
        filePath: [
          { required: true, message: "文件不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询生成试题文件列表 */
    getList() {
      this.loading = true;
      listGenerate_test_paper(this.queryParams).then(response => {
        this.generate_test_paperList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.generate_test_paperList.forEach(item => {
          if (item.filePath != null) {
            // 截取文件名
            this.name = item.filePath.split('/').pop();
            item.filePath = this.name;
          }
        })
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        questionBank: null,
        filePath: null
      };
      this.generatedExamList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生成试题文件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fileId = row.fileId || this.ids
      getGenerate_test_paper(fileId).then(response => {
        this.form = response.data;
        this.generatedExamList = response.data.generatedExamList;
        this.open = true;
        this.title = "修改生成试题文件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.generatedExamList = this.generatedExamList;
          if (this.form.fileId != null) {
            updateGenerate_test_paper(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGenerate_test_paper(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$modal.confirm('是否确认删除生成试题文件编号为"' + fileIds + '"的数据项？').then(function() {
        return delGenerate_test_paper(fileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('generateTest/generate_test_paper/export', {
        ...this.queryParams
      }, `generate_test_paper_${new Date().getTime()}.xlsx`)
    },



    // 生成试题
    showGeneratePaperDialog(row) {
      this.innerVisible = true;
      this.generate_test_form.generate_fileId = row.fileId;
    },
    generate_test_cancel() {
      this.innerVisible = false;
      this.$refs['generate_test_form'].resetFields();
    },
    generate_test_submit() {
      this.$refs['generate_test_form'].validate(valid => {
        if (valid) {
          // 提交表单逻辑
          // this.$message.success('正在生成试题，请稍等......')
          console.log('提交的数据:',this.generate_test_form );
          const loading = this.$loading({
            lock: true,
            text: '生成试题中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          generate(this.generate_test_form)
            .then(response => {
              console.log('响应结果:', response);
              // 根据响应结果处理后续逻辑
              this.$message({
                message: '生成试题成功,请到试题管理中进行下载',
                type: 'success'
              });
              // 触发全局事件通知“gengerate_exam”组件更新数据源
              EventBus.$emit('test-generated');
              loading.close();
            })
            .catch(error => {
              console.error('错误:', error);
              this.$message.error('生成试题失败');
            });

        }
        this.innerVisible = false;
      });
  }


}};
</script>
